﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using DataLib.Accounts.Bus;
using System.Web.Script.Serialization;
using System.Text;
using log4net;

namespace Ewts.ashx
{
    /// <summary>
    /// product 的摘要说明
    /// </summary>
    public class product : IHttpHandler
    {

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.ContentEncoding = System.Text.Encoding.UTF8;

            string strjson = "0";


            if (context.Request["otype"] != null && context.Request["otype"].ToString().Trim()!="")
            {
                string otype = context.Request["otype"].ToString().Trim();
                string barvalue = context.Request["barcode"];
                string operman = context.Request["oper"];
                string outid = context.Request["outid"];
                //string par_barcode = context.Request["barcode"].ToString().Trim();
                //string par_otype = context.Request["otype"].ToString().Trim();
                string par_input = context.Request["barbelong_old"].ToString().Trim();
                string par_output = context.Request["bargraphic_old"].ToString().Trim();
                string oldload = context.Request["oldload"].ToString().Trim();
                switch (otype)
                {

                    case "delBar":  //删除条码
                        strjson = delBarCode(barvalue, operman, outid).ToString();
                        break;
                    case "bar":     //验证条码是否合法
                        strjson = OutBarCodeConfirm(barvalue, otype, par_input, par_output, oldload);
                        break;
                    case "submit":  //出库提交
                       strjson = SaveOutStorage(context.Request["outBar"],
                            outid,
                            context.Request["remark"],
                            operman,
                            par_input,
                            par_output,
                            context.Request["ConsumMan"],
                            context.Request["month"]).ToString();
                        break;
                    default:
                        break;
                }
                
            }

            ////获取出库单号
            //if (context.Request["outtype"] != null && context.Request["outtype"].ToString().Trim() != "")
            //{
            //    strjson = GetOutStorageNo(context.Request["outtype"], context.Request["outid"]);
            //}


            ////验证条码是否合法，返回JSON数组
            //if (context.Request["barcode"] != null && context.Request["barcode"].ToString().Trim() != "")
            //{
            //    string par_barcode = context.Request["barcode"].ToString().Trim();
            //    string par_otype = context.Request["otype"].ToString().Trim();
            //    string par_input = context.Request["barbelong_old"].ToString().Trim();
            //    string par_output = context.Request["bargraphic_old"].ToString().Trim();
            //    string oldload = context.Request["oldload"].ToString().Trim();
            //    strjson = OutBarCodeConfirm(par_barcode, par_otype, par_input, par_output, oldload);
            //}

            ////出库事件提交
            //if (context.Request["outbar"] != null)
            //{

            //    strjson = SaveOutStorage(
            //                context.Request["outBar"],
            //                context.Request["outid"],
            //                context.Request["outno"],
            //                context.Request["oper"],
            //                context.Request["belong"],
            //                context.Request["graphic"],
            //                context.Request["ConsumMan"],
            //                context.Request["saleno"],
            //                context.Request["docusm"],
            //                context.Request["otype"],
            //                context.Request["month"]).ToString();

            //}

            context.Response.Write(strjson);
        }

        #region 出库操作
        ///// <summary>
        ///// 提交以后的出库操作
        ///// </summary>
        ///// <param name="arrbar">所有条形码</param>
        ///// <param name="otype">出库方式</param>
        ///// <param name="belong">归属地</param>
        ///// <param name="consumman">领料人</param>
        ///// <param name="graphic">处理地</param>
        ///// <param name="oper">操作人员</param>
        ///// <param name="outno">出库编号</param>
        ///// <returns></returns>
        //public string AddOutStorage(string[] arrbar, string otype, string outno, string oper, string belong, string graphic, string consumman, string month)
        //{

        //    //取得barcode的Model
        //    //GetModelByCode(arrbar[0]);
        //    int loadid = 0;
        //    string belongcity = belong;
        //    string graphiccity = graphic;
        //    int cjoid = 0;
        //    bool nvflag = true;

        //    for (int i = 0; i < arrbar.Length; i++)
        //    {
        //        if (arrbar[i].Trim() != "")
        //        {
        //            DataLib.Model.BarCode bmodel = new DataLib.BLL.BarCode().GetModelByCode(arrbar[i]);
        //            if (bmodel.loadnumid == 0)
        //            {
        //                //loadid = (int)bmodel.loadnumid;
        //                nvflag = nvflag && false;
        //            }
        //            else if (bmodel.loadnumid != 0)
        //            {
        //                loadid = (int)bmodel.loadnumid;
        //                cjoid = (int)bmodel.cjoid;
        //                nvflag = nvflag && true;
        //                break;
        //            }
        //        }
        //    }

        //    DataLib.BLL.Product oBll = new DataLib.BLL.Product();
        //    //插入outstorage
        //    DataLib.Model.OutStorage oModel = new DataLib.Model.OutStorage();
        //    //User curUser = new User();
        //    //curUser = (User)Session["UserInfo"];

        //    //出库操作人员
        //    oModel.Operator = oper;
        //    oModel.outStorageDate = DateTime.Now;
        //    oModel.ConsumMan = consumman;
        //    oModel.clearmonth = month;
        //    User curUser = new User(oper);
        //    if (curUser != null)
        //    {
        //        if (belongcity != null && belongcity.Trim() != "0")
        //            belongcity = curUser.CompanyCity;
        //        else if (graphiccity != null && graphiccity.Trim() != "0")
        //            graphiccity = curUser.CompanyCity;
        //    }

        //    if (nvflag == true)
        //    {
        //        oModel.VLoadNum = new DataLib.BLL.LoadNum().GetModel(loadid).loadnum;

        //    }
        //    //else
        //    //{
        //    //    oModel.VLoadNum = Code.NumGeneration.GetSerialNum("XN", "VLoadNum");//虚拟Load号
        //    //}

        //    oModel.outStorageType = otype;
        //    oModel.outStorageNo = outno;

        //    //出库编号
        //    //if (oBll.isOutNo(outno) == false)
        //    //{
        //    //    oModel.outStorageNo = outno;
        //    //}
        //    //else
        //    //{
        //    //    oModel.outStorageNo = Code.NumGeneration.GetSerialNum(outno.Substring(0, 1), "OutCode");
        //    //}
          
        //    oModel.status = 1;
        //    oModel.belogarea = belongcity;
        //    oModel.graphicCity = graphiccity;
        //    oModel.id = oBll.Add(oModel);
        //    //if (int.Parse(flag) <= 0)
        //    //    return flag;
        //    //修改barcode数据
        //    decimal onwt = 0;
        //    for (int i = 0; i < arrbar.Length; i++)
        //    {
        //        if (arrbar[i] != null && arrbar[i].ToString().Trim() != "")
        //            onwt += SetBarCodeOut(oModel, arrbar[i]);
        //    }

        //    //出库单重量更新
        //    oModel.totalWeight = onwt;
        //    new DataLib.BLL.OutStorage().Update(oModel);

        //    if ((cjoid != 0) && oModel.outStorageType == "2")
        //    {
        //        DataLib.Model.Cjo cmodel = new DataLib.BLL.Cjo().GetModel(cjoid);
        //        cmodel.status = 5;
        //        new DataLib.BLL.Cjo().Update(cmodel);
        //    }
        //    return oModel.id.ToString();

        //}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="oModel"></param>
        /// <param name="barcode"></param>
        /// <returns></returns>
        //public decimal SetBarCodeOut(DataLib.Model.OutStorage oModel, string barcode)
        //{
        //    //取得barcode的Model

        //    DataLib.Model.BarCode bModel = new DataLib.BLL.BarCode().GetModelByCode(barcode);
        //    //出库方式
        //    switch (bModel.status)
        //    {
        //        case 3:
        //            bModel.status = 4;
        //            break;
        //        case 5:
        //            bModel.status = 6;
        //            break;
        //        case 1:
        //            bModel.status = 2;
        //            break;
        //        case 7:
        //            bModel.status = 8;
        //            break;
        //        case 9:
        //            bModel.status = 10;
        //            break;
        //        default:
        //            bModel.status = -1;
        //            break;
        //    }
        //    bModel.loadnumv = oModel.VLoadNum;
        //    bModel.OutStrorageID = oModel.id;

        //    if (new DataLib.BLL.BarCode().Update(bModel) == false)
        //    {
        //        return 0;
        //    }


        //    //修改storagePosition数据
        //    DataLib.Model.StoragePostion spmodel = new DataLib.BLL.StoragePostion().GetModel((int)bModel.storageid);
        //    spmodel.currvalume -= bModel.qty;
        //    spmodel.currweight -= bModel.nwt;
        //    new DataLib.BLL.StoragePostion().Update(spmodel);

        //    //插入storageData记录
        //    DataLib.Model.StorageData sdmodel = new DataLib.Model.StorageData();
        //    sdmodel.storageid = (int)bModel.storageid;
        //    sdmodel.inoutid = oModel.id;//
        //    sdmodel.barcodeid = bModel.id;
        //    sdmodel.InOrOut = (int)2;
        //    sdmodel.goodscode = bModel.goodscode;
        //    sdmodel.goodsName = bModel.goodsname;
        //    sdmodel.nwt = bModel.nwt;
        //    sdmodel.operDate = oModel.outStorageDate;
        //    sdmodel.storageno = spmodel.storagecode;
        //    sdmodel.operman = oModel.Operator;
        //    sdmodel.goodsid = new DataLib.BLL.Goods().GetgoodsID(sdmodel.goodscode);
        //    sdmodel.startNwt = new DataLib.BLL.StorageData().CurEndNwt(sdmodel.goodscode, sdmodel.storageno);
        //    //sdmodel.startNwt = CurEndNwt(sdmodel.goodscode, pdt.Rows[i]["storageno"].ToString());    //期初净重 
        //    sdmodel.endNwt = sdmodel.startNwt - sdmodel.nwt;
        //    if (new DataLib.BLL.StorageData().Add(sdmodel) > 0)
        //        return (decimal)bModel.nwt;
        //    return (decimal)0;
        //}

   
        /// <summary>
        /// 2015年8月20日 17:39:12 FIFA
        /// </summary>
        /// <param name="cjoid"></param>
        /// <returns></returns>
        public string GetCumtomer(int loadnumid, string loadnum)
        {
            string json = "";
            DataLib.Model.LoadNum lmodel = new DataLib.Model.LoadNum();

            if (loadnum.StartsWith("86"))
            {
                lmodel = new DataLib.BLL.LoadNum().GetModel(loadnumid);
            }
            else
            {
                lmodel.cumcode = "";
                lmodel.cumname = "";
            }
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            json = serializer.Serialize(lmodel);
            return json;
        }

        /// <summary>
        /// 
        /// </summary>
        //public void OperOutStorage(HttpContext context)
        //{
        //    string oper = context.Request["oper"].ToString().Trim();
        //    int outid = int.Parse(context.Request["outid"].ToString().Trim());
        //    DataLib.BLL.OutStorage bll = new DataLib.BLL.OutStorage();
        //    DataLib.Model.OutStorage model = new DataLib.Model.OutStorage();

        //    string strbar = context.Request["outbar"].ToString().Trim();
        //    string strotype = context.Request["otype"].ToString().Trim();
        //    string outno = context.Request["outno"].ToString().Trim();
        //    string consumman = context.Request["ConsumMan"].ToString().Trim();
        //    string belong = context.Request["belong"].ToString().Trim();
        //    string graphic = context.Request["graphic"].ToString().Trim();

        //    model.id = outid;
        //    model.outStorageType = strotype;
        //    model.ConsumMan = consumman;
        //    model.belogarea = belong;
        //    model.graphicCity = graphic;


        //    if (outid == 0)
        //    {
        //        bll.Add(model);
        //    }
        //    else
        //    {
        //        bll.Update(model);
        //    }
        //}

        /// <summary>
        /// 验证BarCode是否合法
        /// </summary>
        /// <param name="barcodevalue"></param>
        /// <param name="outType"></param>
        /// <returns>返回Json数组，Barcode、客户信息、验证结果</returns>
        public string OutBarCodeConfirm(string barcodevalue, string outType, string indepart, string outdepart, string oldload)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string isau = "0";
            string strjson = "";
            DataLib.Model.OutStorage outModel = new DataLib.Model.OutStorage();
            DataLib.BLL.OutStorage outBll = new DataLib.BLL.OutStorage();
            DataLib.Model.BarCode barModel = new DataLib.Model.BarCode();
            DataLib.BLL.BarCode barBll = new DataLib.BLL.BarCode();
            DataLib.BLL.Product bll = new DataLib.BLL.Product();

            barModel = bll.OutBarCodeConfirm(barcodevalue, oldload, ref isau); //outBll.OutBarCodeConfirm(barcodevalue, outType, oldload, ref isau);
            strjson += serializer.Serialize(barModel);

            strjson += ",";
            if (barModel != null && barModel.cjoid != 0)
            {
               strjson += GetCumtomer((int)barModel.loadnumid,barModel.loadnumv);
               if (indepart != null && outdepart != null && indepart != "" && outdepart != "")
               {
                   if (indepart != barModel.barbelong)
                   {
                       isau = "归属地不同";
                   }
                   else if (outdepart != barModel.bargraphic)
                   {
                       isau = "处理地不同";
                   }
               }
            }
            else
            {
                 strjson += "{\"customercode\":\"无\",\"companyname\":\"无\"}";
            }
          


            strjson += ",{\"isau\":\"" + isau + "\",\"indepart\":\"" + indepart + "\",\"outdepart\":\"" + outdepart + "\"}";


            strjson = "[" + strjson + "]";
            return strjson;
        }

        /// <summary>
        /// 获取出库单号，判断是否维护
        /// </summary>
        /// <param name="outtype1"></param>
        /// <param name="outid"></param>
        /// <returns></returns>
        public string GetOutStorageNo()
        {
            string strStorageNo = "";

            strStorageNo = new DataLib.BLL.Product().GetOutNo();
            return strStorageNo;
        }

        /// <summary>
        /// 获取出库是否成功
        /// </summary>
        /// <param name="arrbar"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public int SubmitOutStorage(string arrbar, DataLib.Model.OutStorage model)
        {
            int rowcount = -1;
            DataLib.BLL.Product bll = new DataLib.BLL.Product();
            rowcount = bll.OutStorageSubmit(model, arrbar);
            return rowcount;
        }

        /// <summary>
        /// Model对象传参
        /// </summary>
        /// <param name="arrbar"></param>
        /// <param name="outid"></param>
        /// <param name="remark"></param>
        /// <param name="oper"></param>
        /// <param name="belong"></param>
        /// <param name="graphicCity"></param>
        /// <param name="VLoadNum"></param>
        /// <param name="ConsumMan"></param>
        /// <param name="outStorageType"></param>
        /// <returns></returns>
        public int SaveOutStorage(object arrbar, object outid, object remark, object oper, object belong, object graphicCity, object ConsumMan, object month)
        {
            int rowcount = -1;
           // string ono = outno.ToString();
            string strbarr = "";
            if (arrbar.ToString().Length > 25)
            {
                strbarr = arrbar.ToString().Remove(arrbar.ToString().Length - 1);
            }
            if (outid != null)
            {
                DataLib.Model.OutStorage model = new DataLib.Model.OutStorage();
                DataLib.BLL.OutStorage bll = new DataLib.BLL.OutStorage();
                int outstrid = int.Parse(outid.ToString());
                if (outstrid != 0)
                {
                    model = bll.GetModel(outstrid);
                }
                else
                {
                    model.id = 0;
                    model.outStorageNo = GetOutStorageNo();
                }
                
                model.Operator = oper.ToString();
                model.belogarea = belong.ToString();
                model.graphicCity = graphicCity.ToString();
                model.ConsumMan = ConsumMan.ToString();
                model.outStorageType = "31";
                model.clearmonth = month.ToString();
                model.memo = remark.ToString();
                rowcount = SubmitOutStorage(strbarr, model);

            }
            return rowcount;
        }


        public string GetBarcodeValueArr(string arrbarid)
        {
            string str = "";
            if (arrbarid != "")
            {
                string strtemp = arrbarid.Remove(arrbarid.Length - 1);
                DataTable dt = new DataTable();
                dt = new DataLib.BLL.BarCode().GetBarCodeValue(strtemp);
                if (dt != null && dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        str += dt.Rows[i]["barcodevalue"].ToString();
                        str += ",";
                    }
                    str = str.Remove(str.Length - 1);
                }
            }
            return str;
        }

        /// <summary>
        /// 删除条码
        /// </summary>
        /// <param name="barvalue"></param>
        /// <param name="operman"></param>
        /// <param name="outid"></param>
        /// <returns></returns>
        public int delBarCode(string barvalue, string operman, string outid)
        {
            int rows = 0;
            DataLib.BLL.OutStorage bll = new DataLib.BLL.OutStorage();
            rows = bll.DelBarOut(barvalue, operman, outid);
            return rows;
        }
        #endregion
    }
}